package com.io.nettyflow.clientHandler;

import com.io.model.CustomeMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * Created by yangyx on 2016/7/20.
 */
public class CustomEncoder extends MessageToByteEncoder<CustomeMsg> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, CustomeMsg msg, ByteBuf out) throws Exception {
        System.out.println("------------执行CustomEncoder的encode方法");
        if(null == msg){
            throw new Exception("msg is null");
        }
        String body = msg.getBody();
        byte[] bodyBytes = body.getBytes(Charset.forName("utf-8"));
        out.writeByte(msg.getType());
        out.writeByte(msg.getFlag());
        out.writeInt(bodyBytes.length);
        out.writeBytes(bodyBytes);

    }
}
